package com.demo.crud.aop;

import com.demo.crud.annotations.NotRepeatSubmit;
import com.demo.crud.exception.NotRepeatSubmitException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2019-06-08
 * Time: 16:59
 */
@Component
@Aspect
public class RepeatSubmitAop {

    private final static long LEASE_TIME = 10000L;
    private final static long WAIT_TIME = 500L;
    private AtomicInteger atomicInteger = new AtomicInteger(1);
    /*@Autowired
    private RedissonClient redissonClient;*/

    @Pointcut("@annotation(notRepeatSubmit)")
    public void pointcut(NotRepeatSubmit notRepeatSubmit) {

    }

    /*@Around("pointcut(notRepeatSubmit)")
    public Object around(ProceedingJoinPoint joinPoint, NotRepeatSubmit notRepeatSubmit) throws Throwable {
        System.out.println("around");
        String key = getKey();
        System.out.println(key);
        RLock lock = redissonClient.getLock(key);
        try {
            if (lock.tryLock(WAIT_TIME, LEASE_TIME, TimeUnit.MILLISECONDS)) {
                System.out.println("请求" + atomicInteger.getAndIncrement() + "获得锁");
                Object result = joinPoint.proceed(joinPoint.getArgs());
                return result;
            } else {
                System.out.println("请求" + atomicInteger.getAndIncrement() + "获锁失败");
                throw new NotRepeatSubmitException("禁止重复提交");
            }
        } finally {
            *//*if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }*//*
        }
    }*/

    private String getKey() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        return token;
        //return request.getRequestedSessionId() + request.getRequestURI();
    }
}
